<template>
    <div class="page">
        <h2 class="page-title">新増货主合同</h2>

        <div class="form-grid">
            <div class="form-item required">
                <label>合同标题:</label>
                <input v-model="form.contractTitle" placeholder="请输入合同标题" />
            </div>
            <div class="form-item required">
                <label>货主单位:</label>
                <select v-model.number="form.unitId">
                    <option value="">请选择货主单位</option>
                    <option v-for="u in unitOptions" :key="u.id" :value="u.id">{{ u.name }}</option>
                </select>
            </div>
            <div class="form-item required">
                <label>货主负责人:</label>
                <select v-model.number="form.ownerName">
                    <option value="">请选择货主负责人</option>
                    <option v-for="o in ownerOptions" :key="o.id" :value="o.id">{{ o.name }}</option>
                </select>
            </div>
            <div class="form-item required">
                <label>线 路:</label>
                <input v-model="form.route_infoId" placeholder="请输入线路" />
            </div>
            <div class="form-item">
                <label>货 运 价:</label>
                <input v-model.number="form.tonFreightRate" placeholder="请输入吨运价" type="number" step="0.01" />
            </div>

            <div class="form-item">
                <label>包车金额:</label>
                <input v-model.number="form.charterAmount" placeholder="请输入包车金额" type="number" step="0.01" />
            </div>
            <div class="form-item">
                <label>包车条件吨位:</label>
                <input v-model.number="form.charterConditionTonnage" placeholder="请输入包车条件吨位" type="number"
                    step="0.01" />
            </div>
            <div class="form-item required">
                <label>经 办 人:</label>
                <input v-model="form.handler" placeholder="当前登录人" readonly />
            </div>
            <div class="form-item">
                <label>合同金额:</label>
                <input v-model.number="form.contractAmount" placeholder="请输入合同金额" type="number" step="0.01" />
            </div>

            <div class="form-item">
                <label>签订时间:</label>
                <input type="date" v-model="signingDateStr" />
            </div>

        </div>

        <div class="form-block">
            <label>合同标的或项目说明:</label>
            <textarea v-model="form.contractSubjectDescription" rows="4" placeholder="请输入内容" />
        </div>
        <div class="form-block">
            <label>合同主要条款/变更条款:</label>
            <textarea v-model="form.contractTerms" rows="6" placeholder="请输入内容" />
        </div>

        <!-- 合同文本（附件） -->
        <div class="form-block">
            <label>合同文本（附件）:</label>
            <div class="file-row">
                <input ref="fileInputRef" type="file" multiple @change="onFileChange" />
                <span class="hint">(单个附件最大支持20M，支持: PDF、Word、Excel、Txt格式，可多选)</span>
            </div>
            <div v-if="form.contractAttachments && form.contractAttachments.length" class="file-name">已上传:
                <span v-for="(a, i) in form.contractAttachments" :key="i">
                    <a :href="a" target="_blank">{{ getFileName(a) }}</a><span
                        v-if="i < form.contractAttachments.length - 1">, </span>
                </span>
            </div>
        </div>

        <div class="btn-row">
            <button class="btn primary" :disabled="submitting || uploadingFile" @click="submit(1)">提交审批</button>
            <button class="btn" :disabled="submitting || uploadingFile" @click="cancel">取消</button>
            <button class="btn success" :disabled="submitting || uploadingFile" @click="submit(0)">保存草稿</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { uploadFile } from '@/utils/fileUpload'
import { useRouter } from 'vue-router'
import { write } from '@/assets/Axios/axiosHttple'
import { read } from '@/assets/Axios/axiosHttple'

type Option = { id: number; name: string }

const router = useRouter()

const form = reactive({
    contractNumber: '',
    contractTitle: '',
    unitId: undefined as unknown as number,
    ownerName: undefined as unknown as number,
    route_infoId: '',
    tonFreightRate: undefined as unknown as number,
    charterConditionTonnage: undefined as unknown as number,
    charterAmount: undefined as unknown as number,
    signingDate: '',
    handler: '',
    contractAmount: undefined as unknown as number,
    contractSubjectDescription: '',
    contractTerms: '',
    contractAttachments: [] as string[], // 合同附件列表
    order_infoId: 0,
    processDetail: 0,
    createdAt: '',
    createdBy: '张三'
})

const signingDateStr = computed({
    get() {
        if (!form.signingDate) return ''
        const d = new Date(form.signingDate)
        if (Number.isNaN(d.getTime())) return ''
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${y}-${m}-${day}`
    },
    set(v: string) {
        form.signingDate = v ? new Date(v).toISOString() : ''
    }
})

const unitOptions = ref<Option[]>([])
const ownerOptions = ref<Option[]>([])
const routeOptions = ref<Option[]>([])
// orderOptions removed as dropdown was deleted
// 文件上传相关已移除
const uploadingFile = ref(false)
const submitting = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)

// 从 URL 或路径中提取文件名
function getFileName(urlOrPath: string) {
    try {
        const u = new URL(urlOrPath)
        const segs = (u.pathname || '').split('/')
        return decodeURIComponent(segs[segs.length - 1] || urlOrPath)
    } catch {
        const segs = String(urlOrPath).split(/[\\/\\\\]/)
        return segs[segs.length - 1] || String(urlOrPath)
    }
}

// 多文件上传到后端 FileUpload 接口
async function onFileChange(e: Event) {
    const input = e.target as HTMLInputElement
    const files = input?.files
    if (!files || files.length === 0) return
    uploadingFile.value = true
    try {
        for (let i = 0; i < files.length; i++) {
            const f = files[i]
            const fd = new FormData()
            fd.append('file', f)
            // 若后端需要其他字段（如 folder、policy）可在此追加
            try {
                const fileUrl = await uploadFile(f)
                if (fileUrl) form.contractAttachments.push(fileUrl)
                else form.contractAttachments.push(f.name)
            } catch (err: any) {
                console.warn('上传失败，使用文件名占位', err)
                form.contractAttachments.push(f.name)
            }
        }
    } catch (err: any) {
        console.error('上传错误', err)
        alert(err?.message || '文件上传失败')
    } finally {
        uploadingFile.value = false
        if (fileInputRef.value) fileInputRef.value.value = ''
    }
}

onMounted(async () => {
    // 经办人为当前登录人
    const currentUser = localStorage.getItem('username') || '张三'
    form.handler = currentUser

    // 仅加载货主数据。路由和订单列表接口在当前环境不可用（会返回 404），先不调用它们以避免控制台大量错误。
    await fetchCargoOwners()
})

async function fetchCargoOwners() {
    try {
        if (uploadingFile.value) { alert('文件正在上传，请等待上传完成再提交'); return }
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 2000, t: Date.now() } })
        const block = res?.data?.data ?? res?.data
        const safe = Array.isArray(block?.data) ? block.data : (Array.isArray(block) ? block : [])
        // 单位选项（使用 unitName/company 别名）
        const unitsMap = new Map<number, string>()
        // 负责人选项（使用 ownerName/name 别名）
        const owners: Option[] = []
        for (const it of (safe as any[])) {
            const id = Number(it?.id)
            if (!Number.isFinite(id)) continue
            const unitName = it?.unitName ?? it?.company ?? it?.Company ?? it?.UnitName
            const ownerName = it?.ownerName ?? it?.name ?? it?.OwnerName
            if (unitName && !unitsMap.has(id)) unitsMap.set(id, String(unitName))
            if (ownerName) owners.push({ id, name: String(ownerName) })
        }
        unitOptions.value = Array.from(unitsMap.entries()).map(([id, name]) => ({ id, name }))
        ownerOptions.value = owners
    } catch (e) {
        console.error('获取货主信息失败', e)
    }
}

// 生成自增合同编号（本地计算）：前缀 HD，4位序号，例如 HD0001
async function generateContractNumber(): Promise<string> {
    try {
        // 尝试从后端获取当前最大编号（如果无后端支持，则在本地保存并递增）
        const res = await read.get('contractmanagementread/api/ContractManagement/GetMaxContractNumber', { params: { type: 'cargoOwner' } })
        const max = res?.data?.data ?? res?.data?.max ?? res?.data
        if (typeof max === 'string' && max.startsWith('HD')) {
            const num = Number(max.slice(2))
            if (!Number.isNaN(num)) return `HD${String(num + 1).padStart(4, '0')}`
        }
    } catch { }
    // 后端不可用时使用 localStorage 简单计数器
    try {
        const key = 'local_hd_contract_seq'
        const cur = Number(localStorage.getItem(key) ?? 0) + 1
        localStorage.setItem(key, String(cur))
        return `HD${String(cur).padStart(4, '0')}`
    } catch { return 'HD0001' }
}


// fetchOrders removed because order dropdown was deleted

// order-related helpers removed

function cancel() {
    router.push('/GetCargoOwnerContracts')
}

// onFileChange 已移除

function validate(): boolean {
    if (!form.contractTitle) { alert('请填写合同标题'); return false }
    if (!form.unitId) { alert('请选择货主单位'); return false }
    // 路线改为手动输入，不再强制校验为选择项
    if (!form.handler) { alert('请填写经办人'); return false }
    return true
}

async function submit(processDetail: number) {
    if (!validate()) return
    if (uploadingFile.value) { alert('文件正在上传，请等待上传完成再提交'); return }
    // 强制校验附件至少上传一个
    if (!form.contractAttachments || form.contractAttachments.length === 0) { if (!confirm('未上传附件，是否继续提交？')) return }
    submitting.value = true
    try {
        // 自动生成合同编号，格式 HD0001、HD0002 …
        if (!form.contractNumber) {
            try {
                form.contractNumber = await generateContractNumber()
            } catch (e) {
                // 生成失败时使用默认值
                form.contractNumber = 'HD0001'
            }
        }
        form.processDetail = processDetail
        form.createdAt = new Date().toISOString()
        if (!form.signingDate) form.signingDate = new Date().toISOString()

        // ensure route fields are sent: if user entered a numeric id treat as id, otherwise send as routeName
        const payload: any = { ...form }
        // 附件字段：前端优先以 contractAttachments 数组形式发送，兼容旧字段 contractAttachment（逗号分隔）
        payload.contractAttachments = form.contractAttachments || []
        payload.contractAttachment = Array.isArray(form.contractAttachments) ? form.contractAttachments.join(',') : (form.contractAttachments || '')
        const routeRaw = form.route_infoId
        const maybeNum = Number(routeRaw)
        if (routeRaw !== '' && !Number.isNaN(maybeNum) && String(routeRaw).trim() !== '') {
            payload.route_infoId = maybeNum
            payload.routeName = String(routeRaw ?? '')
        } else {
            payload.route_infoId = 0
            payload.routeName = String(routeRaw ?? '')
        }
        // also include common alias fields so backend can pick up the route name
        payload.routeName = String(payload.routeName ?? '')
        payload.lineName = payload.routeName
        payload.route_name = payload.routeName
        // 统一通过网关写接口提交，按候选顺序尝试
        const candidates = [
            'contractmanagementwrite/api/ContractManagement/CreateCargoOwner/cargo/create',
            'contractmanagementwrite/api/ContractManagement/Create/create',
            'contractmanagementwrite/api/ContractManagement/Create',
            'contractmanagementwrite/api/ContractManagement/Create/cargo/create'
        ]
        let lastErr: any = null
        for (const url of candidates) {
            try {
                const resp = await write.post(url, payload)
                const d = resp?.data ?? {}
                if (resp.status === 200 && (Number(d?.code) === 200 || d?.data === true || typeof d?.data === 'number' || d?.success === true || resp.status === 200)) {
                    alert('提交成功')
                    router.push('/GetCargoOwnerContracts')
                    return
                } else {
                    lastErr = { status: resp?.status, body: d }
                }
            } catch (e) { lastErr = e }
        }
        console.error('创建失败', lastErr)
        alert(lastErr?.body?.message || lastErr?.message || '创建失败')
    } catch (e: any) {
        console.error(e)
        alert(e?.message || '网络异常')
    } finally {
        submitting.value = false
    }
}
</script>

<style scoped>
.page {
    padding: 16px;
}

.page-title {
    font-size: 18px;
    margin: 8px 0 16px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px 24px;
}

.form-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-item>label {
    width: 90px;
    text-align: right;
    color: #333;
}

.form-item.required>label::before {
    content: '*';
    color: #f33;
    margin-right: 4px;
}

.form-item input,
.form-item select {
    flex: 1;
    height: 32px;
    padding: 4px 8px;
}

.form-block {
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-block textarea {
    width: 100%;
    padding: 8px;
}

.file-row {
    display: flex;
    align-items: center;
    gap: 12px;
}

.hint {
    color: #888;
    font-size: 12px;
}

.file-name {
    margin-top: 6px;
    color: #555;
}

.btn-row {
    margin-top: 20px;
    display: flex;
    gap: 12px;
}

.btn {
    height: 32px;
    padding: 0 14px;
    border: 1px solid #3b82f6;
    color: #3b82f6;
    background: #fff;
    cursor: pointer;
}

.btn.primary {
    background: #3b82f6;
    color: #fff;
}

.btn.success {
    border-color: #16a34a;
    color: #16a34a;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>
